from flask import render_template, request, url_for, redirect, flash
from flask_login import login_user, login_required, logout_user, current_user

from watchlist import app, db
from watchlist.models import User, Movie

@app.route('/', methods=['GET','POST'])
@app.route('/template')
@app.route('/home')
@login_required
def index():
    if request.method == 'POST':
        # 获取表单数据
        title = request.form.get('title')
        year = request.form.get('year')

        # 验证数据
        if not title or not len(year) or len(year) > 4 or len(title) > 60:
            # 显示错误提示
            flash('输入无效!', 'warning')
            return redirect(url_for('index'))
        else:
            # 保存数据
            movie = Movie(title=title,year=year)
            db.session.add(movie)
            db.session.commit()
            flash('创建成功', 'ok')
            return redirect(url_for('index'))

    # 读取用户记录
    movies = Movie.query.all() 
    return render_template('index.html',movies=movies)


@app.route('/user/<name>')
def user_page(name):
    return 'User : %s' % escape(name)

@app.route('/movie/edit/<int:movie_id>', methods=['GET', 'POST'])
@login_required
def movie_edit(movie_id):
    movie = Movie.query.get_or_404(movie_id)

    if request.method == 'POST':
        title = request.form['title']
        year = request.form['year']

        # 验证数据
        if not title or not len(year) or len(year) > 4 or len(title) > 60:
            # 显示错误提示
            flash('输入无效!', 'warning')
            return redirect(url_for('movie_edit', movie_id=movie_id))
        else:
            movie.title = title
            movie.year = year
            db.session.commit()
            flash('修改成功', 'ok')
            return redirect(url_for('index'))
    return render_template('edit.html', movie=movie)
            
@app.route('/movie/delete/<int:movie_id>', methods=['POST'])

def movie_delete(movie_id):
    movie=Movie.query.get_or_404(movie_id)
    db.session.delete(movie)
    db.session.commit()
    flash('删除成功', 'ok')
    return redirect(url_for('index'))

@app.route('/test')
def test_url_for():
    # 示例 (在控制台查看)
    print(url_for('home')) # 输出: /
    # 注意
    print(url_for('user_page', name='小鸣'))  #  /user/%E5%B0%8F%E9%B8%A3
    print(url_for('user_page', name='perter'))  # /user/perter
    print(url_for('test_url_for')) # /test
    # 调用传入了多余的关键字参数, 作为查询字符串附加到 URL 后面
    print(url_for('test_url_for', id=123))  # /test?id=123
    return 'Test page'


## 自定义错误页面

# 该视图与之前的视图函数相比, 这个函数返回了一个状态码, 以为普通视图函数默认返回 200, 不用写出
@app.errorhandler(404)
def page_not_found(e):
    # 返回模板和状态码
    return render_template('404.html'), 404 

## 模板上下文处理函数
@app.context_processor
# 函数名称可以随意修改
def inject_user():  
    user = User.query.first();
    # 需要返回字典, 等同于 {'user': user}
    return dict(user = user)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method =='POST':
        username = request.form['username']
        password = request.form['password']
        if not username or not password:
            flash("输入无效!", 'warning')
            return redirect((url_for('login')))
        user = User.query.first();
        # 验证用户名密码是否一直
        if username == user.username and  user.validate_password(password):
            login_user(user) # 登录用户 ,falsk_login 提供
            flash("登录成功", 'ok')
            return redirect(url_for('index'))
        else:
            flash("用户名或密码错误", 'warning')
            return redirect(url_for('login'))

    return render_template('login.html')


#from flask_login import login_required, logout_user
@app.route('/logout')
@login_required # 用于视图保护
def logout():
    logout_user() # 登出用户
    flash('成功登出', 'ok')
    return redirect(url_for('index'))

